package com.gxar.quick.ar.server.base.sdk;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.gxar.common.exception.APIRuntimeException;
import com.gxar.quick.ar.server.base.model.ResultCodeEnum;
import com.gxar.quick.ar.server.base.model.material.info.UploadResultInfo;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * @author linsy
 * @version 1.0
 * @created 2024/4/11 09:22
 */
@Slf4j
public class UploadFileSDK {

    /**
     * 文件上传
     *
     * @param file      文件
     * @param url       url
     * @param token     token
     * @param userId    用户id
     * @param directory 自定义目录
     * @return 文件上传结果
     */
    public static UploadResultInfo upload(File file, String url, String token, String userId, String directory) {
        try (Response response = uploadFile(file, url, token, userId, directory)) {
            ResponseBody body = response.body();
            if (body == null) {
                log.info("文件上传失败body为空");
                throw new APIRuntimeException(ResultCodeEnum.FILE_UPLOAD_FAIL);
            }
            JSONObject object = JSON.parseObject(body.string());
            return object.getObject("data", UploadResultInfo.class);
        } catch (IOException e) {
            log.info("文件上传失败：{}", e.getMessage(), e);
            throw new APIRuntimeException(ResultCodeEnum.FILE_UPLOAD_FAIL);
        }
    }

    private static Response uploadFile(File file, String url, String token, String userId, String directory) {
        try {
            HttpUrl.Builder httpBuilder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();
            httpBuilder.addQueryParameter("product", "quick-ar");
            httpBuilder.addQueryParameter("publics", "true");
            if (StringUtils.isNotBlank(directory)) {
                httpBuilder.addQueryParameter("directory", directory);
            }
            OkHttpClient client = new OkHttpClient();
            RequestBody formBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
                    .addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("text/plain"), file))
                    .build();
            Request request = new Request.Builder().url(httpBuilder.build().url()).header("token", token)
                    .addHeader("user_id", userId).post(formBody).build();
            return client.newCall(request).execute();
        } catch (IOException e) {
            log.error("Upload file failed! user : {}", userId, e);
            throw new APIRuntimeException(e);
        }
    }

}
